package com.cookie.service;

import com.cookie.api.model.DTO.UserDTO;
import com.cookie.api.model.PO.User;
import com.cookie.api.service.UserService;
import com.cookie.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author DELL
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDTO register(UserDTO dto) {
        User user = userRepository.save(dto.getUser());
        return Optional.of(user).map(UserDTO::new)
                .orElseThrow(() -> new RuntimeException("user.register.fail"));
    }

    @Override
    public UserDTO login(UserDTO dto) {
        Optional<User> user = userRepository.findOne(
                Example.of(dto.getUser(),
                        ExampleMatcher.matching()
                                .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.exact())
                                .withMatcher("password", ExampleMatcher.GenericPropertyMatchers.exact())
                )
        );
        return user.map(UserDTO::new)
                .orElseThrow(() -> new RuntimeException("user.login.parse.password.fail"));
    }
}
